package edu.tjhsst.androidIntranet.login;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;

import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import edu.tjhsst.androidIntranet.BrowserLauncher;
import edu.tjhsst.androidIntranet.IntranetManager;
import edu.tjhsst.androidIntranet.TaskPicker;

public class LoginIOThread extends Thread {



	private IntranetLogin il;
	private String username;
	private String password;
	private ProgressDialog loginProgressDialog;
	private final String TAG = "LoginIOThread";
	private boolean keepGoing=true;

	public LoginIOThread(IntranetLogin il, ProgressDialog loginProgressDialog, String username, String password) {
		this.il=il;
		this.loginProgressDialog=loginProgressDialog;
		this.username=username;
		this.password=password;
	}

	public void run() {
		//To override the new SSL certificate of the Intranet. Instructions from http://groups.google.com/group/android-developers/browse_thread/thread/91d5ef794d763814 and http://www.jleeonline.com/?p=25
		HttpsURLConnection.setDefaultHostnameVerifier(new AllVerifier());
		try {
			SSLContext sslContext = SSLContext.getInstance("TLS");
			sslContext.init(null, new TrustManager[] { new AllTrustManager() }, null);
			HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		try {

			String data = URLEncoder.encode("login_username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
			data += "&" + URLEncoder.encode("login_password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");

			URL url = new URL(IntranetManager.SERVER);
			if(!keepGoing) {
				keepGoing=true;
				return;
			}
			URLConnection conn = url.openConnection();
			//conn.setRequestProperty("Referer", IntranetManager.SERVER);
			conn.setRequestProperty("Cookie", "PHPSESSID=deleted");
			//conn.setRequestProperty("Origin", "http://iodine.tjhsst.edu/");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
			wr.write(data);
			wr.flush();

			// Load the page

			Map<String, String> cookies = new HashMap<String, String>();
			String headerName=null;
			for (int i=1; (headerName = conn.getHeaderFieldKey(i))!=null; i++) {
				if (headerName.equalsIgnoreCase("Set-Cookie")) {
					String tempCookie = conn.getHeaderField(i);
					String key = tempCookie.substring(0, tempCookie.indexOf("="));
					String value = tempCookie.substring(tempCookie.indexOf('=')+1, tempCookie.indexOf(';'));
					if(!value.equals("deleted")) {
						//Log.d(TAG , tempCookie + " broken down into " + key + "=" + value + ";");
						cookies.put(key, value);
					}
				}
			}
			String cookieString = "";
			for(String key:cookies.keySet()) {
				cookieString+=key+"="+cookies.get(key)+"; ";
			}

			if(cookieString.length()>1) {
				cookieString=cookieString.substring(0, cookieString.length()-2);
			}

			if(!keepGoing) {
				keepGoing=true;
				return;
			}
			conn = url.openConnection();
			conn.setRequestProperty("Origin", "http://iodine.tjhsst.edu/");
			conn.setRequestProperty("Cookie",cookieString);
			conn.setRequestProperty("Referer", IntranetManager.SERVER);

			StringBuffer page = new StringBuffer();

			BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = rd.readLine()) != null) {
				page.append(line);
			}
			wr.close();
			rd.close();

			Pattern loggedIn = Pattern.compile("<title>TJHSST Intranet2: News</title>");
			Pattern uid = Pattern.compile("<a href=\"https://iodine.tjhsst.edu/eighth/vcp_schedule/view/uid/(\\d+?)\">Full Schedule</a>");

			Matcher m = loggedIn.matcher(page);
			if(m.find()) {
				Log.d(TAG, "Found logged in title");
				IntranetManager.setCookies(cookieString);
				Matcher u = uid.matcher(page);
				if(u.find()) {
					Log.d(TAG, "Found UID:" + u.group(1));
					IntranetManager.setUID(u.group(1));
				}
				
			}

			loginProgressDialog.dismiss();
			if(IntranetManager.isLoggedIn()) {
				Log.d(TAG, "Login Successful");

				il.saveLogin();

				il.startActivity(new Intent(il, TaskPicker.class));
			} else {
				Log.d(TAG, "Login Failed");

				IntranetManager.showErrorMessage(il, "Login Failed. Please check your username and password and try again.");
			}
		} catch(IOException e) {
			e.printStackTrace();
		}
	}

	public void stopLoggingIn() {
		keepGoing=false;
	}
}
